<template>
  <div class="content-wrapper">
    <div class="top-search-box">
      <!-- 高级查询 -->
      <a-form v-bind="layout" ref="formRef" :model="queryForm">
        <a-row :gutter="16">
          <a-col v-bind="colLayout.cols">
            <a-form-item label="文件名">
              <a-input v-model:value="queryForm.fileName" placeholder="请输入文件名" :allow-clear="true" @pressEnter="handleQuery" />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols">
            <a-form-item label="模块名">
              <a-input v-model:value="queryForm.moduleName" placeholder="请输入模块名" :allow-clear="true" @pressEnter="handleQuery" />
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols">
            <a-form-item label="状态">
              <a-select
                v-model:value="queryForm.status"
                :get-popup-container="(triggerNode) => triggerNode.parentNode"
                option-filter-prop="children"
                show-search
                :allow-clear="true"
                placeholder="请选择状态"
              >
                <a-select-option key="1" value="1">导出成功</a-select-option>
                <a-select-option key="0" value="0">正在导出中</a-select-option>
                <a-select-option key="2" value="2">导出异常</a-select-option>
                <!-- <a-select-option v-for="item in statusList" :key="item.sysLookupTlId" :value="item.lookupCode">
                  {{ item.lookupName }}
                </a-select-option> -->
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colLayout.cols" style="margin-left: auto">
            <div class="table-page-search-submitButtons">
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  <search-outlined />
                  查询
                </a-button>
                <a-button type="primary" ghost @click="resetQuery">
                  <redo-outlined />
                  清空
                </a-button>
                <!-- <a-button type="link" style="margin: 0" @click="toggleAdvanced">
                  {{ advanced ? '收起' : '展开' }}
                  <up-outlined v-if="advanced" />
                  <down-outlined v-else />
                </a-button> -->
              </a-space>
            </div>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 表格组件 -->
    <div class="table-wrapper">
      <AvicTable
        ref="sysDownloadFiles"
        table-key="sysDownloadFiles"
        :columns="columns"
        :row-key="(record) => record.id"
        :data-source="list"
        :loading="loading"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          columnWidth: 40,
          fixed: true
        }"
        :page-parameter="queryParam.pageParameter"
        :total="totalPage"
        @change="handleTableChange"
        @refresh="getList"
      >
        <template #toolBarLeft>
          <a-space>
            <!-- 暂未支持批量下载 -->
            <!-- <a-button type="primary" title="下载" @click.stop="handleDownloadHeader(selectedRowKeys[0])">
              <template #icon><download-outlined /></template>
              下载
            </a-button> -->
            <a-button
              title="删除"
              danger
              :type="selectedRowKeys.length == 0 ? 'default' : 'primary'"
              :loading="delLoading"
              @click="handleDelete(selectedRowKeys, '')"
            >
              <template #icon>
                <delete-outlined />
              </template>
              删除
            </a-button>
          </a-space>
        </template>
        <!-- <template #toolBarRight>
          <a-input-search
            class="opt-btn-commonsearch"
            style="width: 200px"
            placeholder="请输入方法名或文件路径"
            :allow-clear="true"
            @search="handleKeyWordQuery"
          />
        </template> -->
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'id'">
            {{ index + 1 + queryParam.pageParameter.rows * (queryParam.pageParameter.page - 1) }}
          </template>
          <template v-else-if="column.dataIndex === 'medthonName'">
            <a @click="handleDetail(record)">
              {{ record.medthonName }}
            </a>
          </template>
          <template v-else-if="column.dataIndex === 'creationDate'">
            <span :title="proxy.$dayjs(record.creationDate).format('YYYY-MM-DD HH:mm:ss')">
              {{ proxy.$dayjs(record.creationDate).format('YYYY-MM-DD HH:mm:ss') }}
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'status'">
            <span v-if="record.status === '正在导出中'" style="color: #1f76cb">{{ record.status }}</span>
            <span v-else-if="record.status === '导出异常'" style="color: red">
              <a-tooltip :title="record.errorInfo" color="red">
                {{ record.status }}
              </a-tooltip>
            </span>
            <span v-else style="color: green">{{ record.status }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'successCount'">
            <a-progress
              :stroke-color="{
                '0%': '#108ee9',
                '100%': '#87d068'
              }"
              :percent="parseFloat((record.successCount / record.allCount).toFixed(2)) * 100"
            />
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <!-- <a-button type="link" class="inner-btn" @click.stop="handleEdit(record.id)">编辑</a-button> -->
            <a-button type="link" :disabled="record.status !== '导出成功'" class="inner-btn" @click.stop="handleDownload(record.id)">
              下载
            </a-button>
            <a-button
              type="link"
              :disabled="record.status === '正在导出中'"
              class="inner-btn"
              @click.stop="handleDelete([record.id], 'row')"
            >
              删除
            </a-button>
          </template>
        </template>
      </AvicTable>
    </div>
    <!-- 添加页面弹窗 -->
    <sys-download-files-add v-if="showAddModal" ref="addModal" @reloadData="getList" @close="showAddModal = false" />
    <!-- 编辑页面弹窗 -->
    <sys-download-files-edit v-if="showEditModal" ref="editModal" :form-id="formId" @reloadData="getList" @close="showEditModal = false" />
    <!-- 详情页面弹窗 -->
    <sys-download-files-detail v-if="showDetailModal" ref="detailModal" :form-id="formId" @close="showDetailModal = false" />
    <AvicExcelImport
      v-if="showImportModal"
      :form-data="excelParams"
      title="单表模板导入"
      import-url="/demo/sysdownloadfiless/importData/v1"
      download-template-url="/demo/sysdownloadfiless/downloadTemplate/v1"
      @reloadData="getList"
      @close="showImportModal = false"
    />
  </div>
</template>
<script lang="ts" setup>
import type { SysDownloadFilesDto } from '@/api/avic/system/SysDownloadFilesApi'; // 引入模块DTO
import { listSysDownloadFilesByPage, delSysDownloadFiles, downloadFiles } from '@/api/avic/system/SysDownloadFilesApi';
import SysDownloadFilesAdd from './SysDownloadFilesAdd.vue'; // 引入添加页面组件
import SysDownloadFilesEdit from './SysDownloadFilesEdit.vue'; // 引入编辑页面组件
import SysDownloadFilesDetail from './SysDownloadFilesDetail.vue'; // 引入详情页面组件
const { proxy } = getCurrentInstance();
const layout = {
  labelCol: { flex: '0 0 120px' },
  wrapperCol: { flex: '1 1 0' }
};
const colLayout = proxy.$colLayout4; // 页面表单响应式布局对象
const columns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    ellipsis: true,
    minWidth: 200,
    resizable: true,
    align: 'left'
  },
  {
    title: '模块名',
    dataIndex: 'moduleName',
    ellipsis: true,
    minWidth: 120,
    width: 150,
    resizable: true,
    align: 'left'
  },
  {
    title: '状态',
    dataIndex: 'status',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'center'
  },
  {
    title: '总条数',
    dataIndex: 'allCount',
    width: 100,
    resizable: true,
    align: 'center'
  },
  {
    title: '下载进度',
    dataIndex: 'successCount',
    width: 200,
    resizable: true,
    align: 'center'
  },
  {
    title: '文件大小',
    dataIndex: 'remark',
    ellipsis: true,
    width: 100,
    resizable: true,
    align: 'right'
  },
  {
    title: '创建时间',
    dataIndex: 'creationDate',
    width: 180,
    resizable: true,
    align: 'center'
  },
  {
    title: '创建人',
    dataIndex: 'createdBy',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    ellipsis: true,
    width: 120,
    fixed: 'right',
    align: 'center'
  }
];
const queryForm = ref<SysDownloadFilesDto>({});
const queryParam = reactive({
  // 请求表格数据参数
  pageParameter: {
    page: 1, // 页数
    rows: 20 // 每页条数
  },
  searchParams: {
    // ...queryForm
  },
  keyWord: ref(''), // 快速查询数据
  sidx: null, // 排序字段
  sord: null // 排序方式: desc降序 asc升序
});
const showAddModal = ref(false); // 是否展示添加弹窗
const showEditModal = ref(false); // 是否展示编辑弹窗
const showDetailModal = ref(false); // 是否展示详情弹窗
const showImportModal = ref(false); // 是否展示导入弹窗
const excelParams = ref({ tableName: 'sysDownloadFiles' }); // 导入Excel数据过滤参数
const list = ref([]); // 表格数据集合
const formId = ref(''); // 当前行数据id
const selectedRowKeys = ref([]); // 选中数据主键集合
const loading = ref(false);
const delLoading = ref(false);
const totalPage = ref(0);

onMounted(() => {
  // 加载表格数据
  getList();
});

/** 查询数据  */
function getList() {
  selectedRowKeys.value = []; // 清空选中
  loading.value = true;
  listSysDownloadFilesByPage(queryParam)
    .then((response) => {
      list.value = response.data.result;
      totalPage.value = response.data.pageParameter.totalCount;
      loading.value = false;
    })
    .catch(() => {
      list.value = [];
      totalPage.value = 0;
      loading.value = false;
    });
}
/** 高级查询 查询按钮操作 */
function handleQuery() {
  queryParam.searchParams = queryForm.value;
  queryParam.keyWord = '';
  queryParam.pageParameter.page = 1;
  getList();
}
/** 高级查询 重置按钮操作 */
function resetQuery() {
  queryForm.value = {};
  handleQuery();
}
/** 高级查询 展开/收起 */
// function toggleAdvanced() {
//   advanced.value = !advanced.value;
// }
/** 快速查询逻辑 */
// function handleKeyWordQuery(value) {
//   const keyWord = {
//     medthonName: value,
//     fileUrl: value
//   };
//   queryParam.keyWord = JSON.stringify(keyWord);
//   queryParam.pageParameter.page = 1;
//   getList();
// }
/** 详细 */
function handleDetail(record) {
  formId.value = record.id;
  showDetailModal.value = true;
}
/** 删除 */
function handleDelete(ids, type) {
  if (ids.length === 0) {
    proxy.$message.warning('请选择要删除的数据！');
    return;
  }
  proxy.$confirm({
    title: `确认要删除${type === 'row' ? '当前行的' : '选择的'}数据吗?`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      delLoading.value = true;
      delSysDownloadFiles(ids)
        .then((res) => {
          if (res.success) {
            proxy.$message.success('删除成功！');
            getList();
          }
          delLoading.value = false;
        })
        .catch(() => {
          delLoading.value = false;
        });
    }
  });
}
/** 勾选复选框时触发 */
function onSelectChange(rowKeys) {
  selectedRowKeys.value = rowKeys;
}
/** 表格排序 */
function handleTableChange(pagination, filters, sorter) {
  queryParam.pageParameter.page = pagination.current;
  queryParam.pageParameter.rows = pagination.pageSize;
  if (proxy.$objIsNotBlank(sorter.field)) {
    queryParam.sidx = sorter.field;
    queryParam.sord = sorter.order === 'ascend' ? 'asc' : 'desc'; // 排序方式: desc降序 asc升序
  }
  getList();
}
/**
 * 操作列的文件下载
 * @param fileId 文件ID
 */
function handleDownload(fileId) {
  downloadFiles(fileId).then(() => {
    loading.value = false;
    proxy.$message.info('下载成功！');
  });
}
</script>
